import React, { useState } from "react";
import { Button, Space, Table, Upload, Image } from "antd";
import type { GetProp, TableProps, UploadProps } from "antd";
import { formatFileSize } from "./utils";

type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0] & {
  url: "";
  originFileObj: File;
};

const defaultColumns: TableProps<FileType>["columns"] = [
  {
    title: "名称",
    dataIndex: "name",
    key: "name",
    render: (val, item) => (
      <>
        <Image width={40} src={URL.createObjectURL(item?.originFileObj)} />
        <a>{val}</a>
      </>
    ),
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
  },
  {
    title: "原始大小",
    dataIndex: "size",
    key: "size",
    render: (val: number) => {
      return (
        <>
          <span>{formatFileSize(val)} </span>{" "}
        </>
      );
    },
  },
  {
    title: "压缩大小",
    dataIndex: "address",
    key: "address",
  },
  {
    title: "压缩率",
    dataIndex: "address",
    key: "address",
  },
];

//获取base64数据
const getBase64 = (file: FileType): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

// TODO 对每个图片设置尺寸, 压缩参数等...配置项
// 是否可以接入不同压缩工具做适配, 找到合适压缩的

const App: React.FC = () => {
  const [data, setData] = useState([]);

  const handleChange = (e: any) => {
    // const url = URL.createObjectURL(e.file.originFileObj); //这样不行?
    // console.log(url);
    // getBase64(e.file.originFileObj).then((res: any) => {
    //   console.log(res, 11);
    // });
    setData(e.fileList);
    console.log(e);
  };

  const handleDel = (res: FileType) => {
    const index = data.findIndex((item: FileType) => item?.uid === res.uid);
    data.splice(index, 1);
    setData([...data]); //引用类型不变, 所以不会变化
  };

  const handleClear = () => {
    while (data.length > 0) {
      data.splice(0, 1);
    }
    setData([]);
  };

  const uploadProps = {
    accept: "image/*",
    maxCount: 10,
    multiple: true,
    showUploadList: false,
    customRequest: () => {},
    onChange: handleChange,
  };

  const columns = [
    ...defaultColumns,
    {
      title: "操作",
      key: "action",
      render: (_: any, item: FileType) => (
        <Space size="middle">
          <a>保存</a>
          <a>复制 base64</a>
          <a onClick={() => handleDel(item)}>删除</a>
        </Space>
      ),
    },
  ];

  return (
    <>
      <Space style={{ marginBottom: 16 }}>
        <Upload {...uploadProps}>
          <Button type="primary">选择图片</Button>
        </Upload>

        <Button type="default">批量下载</Button>
        <Button type="default" onClick={handleClear}>
          清空列表
        </Button>
      </Space>
      <Table rowKey={"uid"} columns={columns} dataSource={data} />
    </>
  );
};

export default App;
